package mobile.game.common.net;

import java.util.List;

import mobile.game.core.Chunk;
import mobile.game.core.Service;
import mobile.game.core.gen.proxy.DistrClass;
import mobile.game.core.gen.proxy.DistrMethod;
import mobile.game.core.support.ConnectionStatus;
import mobile.game.core.support.ServerDistrConfig;

@DistrClass(
		servId = ServerDistrConfig.SERV_CONN,
		importClass = {List.class, Chunk.class}
		)
public class ConnService extends Service {

	public ConnService(String servId) {
		super(servId);
	}
	
	@Override
	public Object getId() {
		return ServerDistrConfig.SERV_CONN;
	}
	
	/**
	 * 检查连接是否还存在
	 * 因为各种特殊原因，会出现连接已断开，但是游戏服务器没有清理的BUG
	 * 出现这种问题后，发送的消息会不停报错，影响系统稳定
	 * @param connId
	 */
	@DistrMethod
	public void check(long connId) {
		Service serv = port.getService(connId);
		
		port.returns(serv != null);
	}

	/**
	 * 群发消息
	 * @param connIds
	 * @param msgId
	 * @param msgbuf
	 */
	@DistrMethod
	public void sendMsg(List<Object> connIds, int msgId, Chunk msgbuf) {
		for(Object connId : connIds) {
			Service serv = port.getService(connId);
			if(serv == null) {
				continue;
			}
			
			Connection connection = (Connection)serv;
			connection.sendMsg(msgId, msgbuf);
		}
	}
	
	@DistrMethod
	public void sendMsg(List<Object> connIds, List<Integer> idList, List<Chunk> chunkList) {
		for(Object connId : connIds) {
			Service serv = port.getService(connId);
			if(serv == null) {
				continue;
			}
			
			Connection connection = (Connection)serv;
			connection.sendMsg(idList, chunkList);
		}
	}
	
	/**
	 * 群发消息至全体
	 * TODO 以后改为使用ChannelGroup方式
	 * 		但由于ChannlGroup没有isWritable函数，所有待确认后再换
	 * @param msgId
	 * @param msgbuf
	 */
	@DistrMethod
	public void sendMsgToAll(int msgId, Chunk msgbuf) {
		for(Service serv : port.getServices()) {
			// port上service还有connService，所有必须排除
			if(!(serv instanceof Connection)) {
				continue;
			}
			
			Connection connection = (Connection)serv;
			if(connection.getStatus().step == ConnectionStatus.STATUS_PLAYING) {
				connection.sendMsg(msgId, msgbuf);
			}
		}
	}
}
